package com.zretc.support.controller;

import com.zretc.support.entity.Course;
import com.zretc.support.entity.CourseData;
import com.zretc.support.service.CourseService;
import com.zretc.support.tool.PageData;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("api/course")
public class CourseController {

    @Autowired
    CourseService courseService;

    Logger logger = LoggerFactory.getLogger(CourseController.class);

    @GetMapping("listcourse")
    @ApiOperation(value = "课程分页查询",notes = "分页")
    public PageData<Course> listCourse(@RequestParam(name = "keywords", defaultValue = "",required = false) String keywords, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int limit) {

        Page<Course> pg = courseService.getCourseByPage(keywords, page, limit);
        PageData<Course> pd = new PageData<Course>();
        pd.setCode(0);
        pd.setRecords(pg.getContent());
        pd.setTotal((int) pg.getTotalElements());
        pd.setSize(pg.getSize());
        pd.setMsg("");
        pd.setCurrent(pg.getNumber() + 1);
        return pd;
    }
    @GetMapping("listcoursebytea")
    @ApiOperation(value = "课程分页查询",notes = "分页")
    public PageData<Course> listCourseByTea(@RequestParam(name = "keywords", defaultValue = "",required = false) String keywords, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int limit) {

        Page<Course> pg = courseService.getCourseByPageByTea(keywords, page, limit);
        PageData<Course> pd = new PageData<Course>();
        pd.setCode(0);
        pd.setRecords(pg.getContent());
        pd.setTotal((int) pg.getTotalElements());
        pd.setSize(pg.getSize());
        pd.setMsg("");
        pd.setCurrent(pg.getNumber() + 1);
        return pd;
    }

    @GetMapping("listcoursebyteacher")
    @ApiOperation(value = "根据教师课程分页查询",notes = "分页")
    public PageData<Course> listCourseByTeacher(@RequestParam(name = "userId", defaultValue = "001",required = false) String userId,@RequestParam(name = "keywords", defaultValue = "",required = false) String keywords, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int limit) {

        Page<Course> pg = courseService.getCourseByTeacher(userId,keywords ,page, limit);
        PageData<Course> pd = new PageData<Course>();
        pd.setCode(0);
        pd.setRecords(pg.getContent());
        pd.setTotal((int) pg.getTotalElements());
        pd.setSize(pg.getSize());
        pd.setMsg("");
        pd.setCurrent(pg.getNumber() + 1);
        return pd;

    }

    @GetMapping("listcoursebystudent")
    @ApiOperation(value = "根据学生课程分页查询",notes = "分页")
    public PageData<Course> listCourseByStudent(@RequestParam(name = "userId", defaultValue = "002",required = false) String userId,@RequestParam(name = "keywords", defaultValue = "",required = false) String keywords, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int limit) {

        Page<Course> pg = courseService.getCourseByStudent(userId,keywords, page, limit);
        PageData<Course> pd = new PageData<Course>();
        pd.setCode(0);
        pd.setRecords(pg.getContent());
        pd.setTotal((int) pg.getTotalElements());
        pd.setSize(pg.getSize());
        pd.setMsg("");
        pd.setCurrent(pg.getNumber() + 1);
        return pd;

    }

    @PostMapping("addcourse")
    @ApiOperation(value = "课程添加")
    public Course addCourse(@RequestBody Course course){
        return courseService.addCourse(course);
    }

    /**
     * 资料上传
     * @param multipartfiles
     * @param a
     * @param courseId
     * @return
     * @throws IOException
     */
    @RequestMapping("/save/{courseId}")
    public Course save(@RequestParam("multipartfiles") MultipartFile[] multipartfiles,String a ,@PathVariable(value = "courseId")Long courseId) throws IOException {
        //获取项目编译之后的文件路径，一般是“项目路径/target/classes”
        Course course = courseService.getCourseById(courseId);
        String Path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")+"static/swagger/")).replaceAll("file:/", "").replaceAll("%20", " ").trim();
        if(Path.indexOf(":") != 1){
            Path = File.separator + Path;
        }
        //遍历文件
        if(multipartfiles != null && multipartfiles.length>0){
            for(MultipartFile item : multipartfiles){
                String fileName = item.getOriginalFilename();//获取文件名
                String filePath = Path + "uploadFiles/uploadFiles";//自定义上传路径
                logger.info("filepath:"+filePath);
                File file = new File(filePath,fileName);
                if(!file.exists()){//判断文件夹是否存在，如果不存在则创建
                    if(!file.getParentFile().exists()){
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                }
                item.transferTo(file);//上传文件
                if (course.getCourseData().equals("")){
                    course.setCourseData(fileName);
                }else {
                    course.setCourseData(course.getCourseData()+","+fileName);
                }
            }
        }
        return courseService.updateCourse(course);
    }

    @PostMapping("updatecourse")
    @ApiOperation(value = "课程修改")
    public Course updateCourse(@RequestBody Course course){
        return courseService.updateCourse(course);
    }

    @GetMapping("deletecourse/{courseId}")
    @ApiOperation(value = "课程删除")
    public String deleteCourse(@PathVariable("courseId") Long courseId){
        courseService.deleteCourse(courseId);
        return "删除成功";
    }

    //课程资料的下载
    @RequestMapping("/download/{classId}/{index}")
    public void download(@PathVariable("classId") Long classId,@PathVariable("index") int index, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取文件的绝对路径
        String realPath =  (String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")+"static/swagger/")).replaceAll("file:/", "").replaceAll("%20", " ").trim()+"uploadFiles/uploadFiles/";
        //获取输入流对象（用于读文件）
        List<String> list = Arrays.asList(courseService.getCourseById(classId).getCourseData().split(","));
        String fileName=list.get(index);
        FileInputStream fis = new FileInputStream(new File(realPath, fileName));
        //获取文件后缀（.txt）
        String extendFileName = fileName.substring(fileName.lastIndexOf('.'));
        //动态设置响应类型，根据前台传递文件类型设置响应类型
        response.setContentType(request.getSession().getServletContext().getMimeType(extendFileName));
        //设置响应头,attachment表示以附件的形式下载，inline表示在线打开
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        //获取输出流对象（用于写文件）
        ServletOutputStream os = response.getOutputStream();
        //下载文件,使用spring框架中的FileCopyUtils工具
        FileCopyUtils.copy(fis,os);

    }

    @GetMapping(value = "getcoursebyid/{courseId}")
    public Course getCourseById(@PathVariable(value = "courseId") long courseId){
        return courseService.getCourseById(courseId);
    }

    @GetMapping(value = "getcoursedatabyid/{courseId}")
    public List<CourseData> getCourseDataById(@PathVariable(value = "courseId") long courseId){
        List<CourseData> courseDataList = new ArrayList<CourseData>();
        if(courseService.getCourseById(courseId).getCourseData().equals("")){
            courseDataList=null;
        }else {
            List<String> list = Arrays.asList(courseService.getCourseById(courseId).getCourseData().split(","));
            for (int i = 0;i<list.size();i++){
                courseDataList.add(i,new CourseData(i,list.get(i)));
            }
        }
        return courseDataList;
    }

    @RequestMapping("/deletecoursedata/{classId}/{index}")
    public List<CourseData> deletecoursedata(@PathVariable("classId") Long classId,@PathVariable("index") int index)  {
        String data = "";
        List<CourseData> courseDataList = new ArrayList<CourseData>();
        List<String> list = Arrays.asList(courseService.getCourseById(classId).getCourseData().split(","));
        if (list.size()==1&&index==0){

        }else {
            for (int i = 0;i<list.size();i++){
                courseDataList.add(i,new CourseData(i,list.get(i)));
            }
            courseDataList.remove(index);
            for (int j = 0 ;j<courseDataList.size();j++){
                data+=courseDataList.get(j).getDataName()+",";
            }
            data = data.substring(0,data.length()-1);
        }

        Course c = getCourseById(classId);
        c.setCourseData(data);
        courseService.updateCourse(c);

        return getCourseDataById(classId);

    }

    // 根据课程编号获取课程名称  -- hq
    @RequestMapping(value = "getCouById/{courseId}")
    public String getCourseNameByCourseId(@PathVariable("courseId") int courseId){
        return courseService.getCourseById((long) courseId).getCourseName();
    }

    // 获取所有课程编号 -- hq
    @RequestMapping(value = "getCouAll")
    public List<Course> getAllCourse(){
        return courseService.getAllCourse();
    }

    //获取教师所受课程编号
    @RequestMapping(value = "getCouAllByTea/{userId}")
    public List<Course> getAllCourseByTea(@PathVariable(value = "userId") String userId){
        return courseService.getAllCourseByTea(userId);
    }

}
